package org.BUPT.application.service;

import org.BUPT.domain.model.message.MessageBO;
import org.BUPT.infrastructure.persistent.po.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class MessageService {
    final static String[] midStrings ={
            "回答了你提出的问题",
            "评论了您的回答",
            "评论了您的评论",
            "赞同了您的回答",
            "关注了你的问题",
            "更新了您回答的问题",
            "更新了您关注的问题",
            "的提问等您来答"
    };
    @Autowired
    org.BUPT.domain.service.MessageService messageService;

    public void addMessage(MessageBO messageBO){
        Message message = new Message()
                .setCreateTime(new Date())
                .setQuestionId(messageBO.getQuestionId())
                .setDestUserId(messageBO.getDestUserId())
                .setOriUserId(messageBO.getOriUserId())
                .setType(messageBO.getType())
                .setIsRead(0);
        messageService.addMessage(message);
    }
    protected MessageBO trans(Message message){
        return new MessageBO(
                message.getQuestionId(),
                message.getOriUserId(),
                message.getDestUserId()
        ) {
            @Override
            public int getType() {
                return message.getType();
            }

            @Override
            public String getMidString() {
                return midStrings[getType()-1];
            }
        }
                .setCreateTime(message.getCreateTime());
    }
    public List<MessageBO> getMessageBOsfUser(int userId){
        List<Message> messages = messageService.getMessagesOfUser(userId);
        List<MessageBO> messageBOs = new ArrayList<>();
        for (Message message:messages){
            MessageBO messageBO = trans(message);
            messageBOs.add(messageBO);
        }
        return messageBOs;
    }

    public void visitMessage(int messageId){
        MessageBO messageBO = trans(messageService.getMessage(messageId));
        messageBO.setIsRead(1);
        addMessage(messageBO);
    }

}
